$(document).ready(function () {
    var username, token;
    if (location.hash !== '') {
        var hash = location.hash.split('@');
        $('a').attr('href', $('a').attr('href') + location.hash);
        username = hash[0].substring(1);
        token = hash[1];
        sessionStorage.setItem('username', username);
        sessionStorage.setItem('token', token);
    } else if(sessionStorage.getItem('username')) {
        username = sessionStorage.getItem('username');
        token = sessionStorage.getItem('token');
    } else {
        location.href = '/login';
    }
    checkLogin(username, token);
//    setInterval('checkLogin(username, token)', 1000);

    $.ajax({
        url: '/getIdAndUsersP',
        method: 'get',
        data: {
            appFlag: 1,
            username: username
        },
        dataType: 'jsonp'
    }).done(function (data) {
        var tr = $('<tr></tr>')
        $('<td></td>').html(data.username).appendTo(tr);
        $('<td></td>').html(data.roles.join(' ')).appendTo(tr);
        $('<td></td>').html(data.authorities.join(' ')).appendTo(tr);
        $('table tbody').append(tr);
    })
    $('#exit').click(function () {
        $.ajax({
            url: '/logout',
            method: 'get',
            data: {username: username},
            dataType: 'jsonp'
        }).done(function (data) {
            sessionStorage.removeItem('username');
            sessionStorage.removeItem('token');
            location.href = '/login';
        });

    });
});

function checkLogin(username, token) {
    $.ajax({
        url: '/checkLogin',
        method: 'get',
        data: {
            username: username,
            token: token
        },
        dataType: 'jsonp'
    }).done(function (data) {
        console.log('check');
        if (data.result === false) {
            location.href = '/login';
        }
    });
}